package my.framework.web;

import my.framework.anno.RequestMapping;
import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于加载Controller映射信息
 *
 */
public class ControllerMappingManager {

	private Map<String, ControllerMapping> controllerMappings = new HashMap<String, ControllerMapping>();

	/**
	 * 构造方法
	 * 
	 * @param webPackage
	 *            配置文件名
	 */
	public ControllerMappingManager(String webPackage) {
		init(webPackage);
	}

	/**
	 * init方法用来加载Controller配置文件。
	 * 
	 * @param webPackage
	 *            配置文件名
	 */
	public void init(String webPackage) {
		System.out.println("ControllerMappingManager 初始化.......");
		// 获取项目的根目录
		String rootPath = this.getClass().getResource("/").getPath();
		//拆分包名，拼接包路径
		String [] packageNames= webPackage.split("\\.");
		for(int i=0; i<packageNames.length; i++){
			rootPath+=packageNames[i]+"/";
		}
		// 创建Controller目录的对象
		File file = new File(rootPath);
		// 获取目录下所有的文件
		File[] files = file.listFiles();
		for (File tempFile : files) {
			//获得文件名,利用replaceAll替换.class后缀
			String className = tempFile.getName().replaceAll(".class", "");
			try {
				Class<?> clazz = Class.forName(webPackage+"." + className);
				//获取该类的所有方法
				Method[] declaredMethods = clazz.getDeclaredMethods();
				for (Method declaredMethod : declaredMethods) {
					//循环判断方式是否添加了@RequestMapping注解
					if (declaredMethod.isAnnotationPresent(RequestMapping.class)) {
						//得到该方法上添加了@RequestMapping注解的对象
						RequestMapping declaredAnnotation =
								declaredMethod.getDeclaredAnnotation(RequestMapping.class);

						// 创建ControllerMapping对象，设置类名和方法名
						ControllerMapping controllerMapping=new ControllerMapping();
						controllerMapping.setClassName(webPackage+"."+className);
						controllerMapping.setMethodName(declaredMethod.getName());
						controllerMappings.put(declaredAnnotation.value(), controllerMapping);
					}
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		System.out.println("map==============>"+controllerMappings);
	}

	/**
	 * 根据映射信息查询对应的ControllerMapping实例。
	 * 
	 * @param path
	 * @return ControllerMapping
	 */
	public ControllerMapping getControllerMapping(String path) {
		return this.controllerMappings.get(path);
	}
	
	/**
	 * 判断是否存在对应的映射信息。
	 * 
	 * @param path
	 * @return
	 */
	public boolean containsKey(String path) {
		return this.controllerMappings.containsKey(path);
	}

	/**
	 * @return 返回所有Controller映射信息
	 */
	public Map<String, ControllerMapping> getControllerMappings() {
		return this.controllerMappings;
	}
}